import {Inject} from 'plugins'
import config from 'config';

@Inject('$timeout', '$scope', '$sce', '$state', 'ui.http', 'ui.dialog', 'ui.api', 'SourceService')
export default class Task {
	constructor($timeout, $scope, $sce, $state, http, dialog, api, service) {
		var q = $scope.q = {};

		// $scope.add = function() {
		// 	api.form({
		// 		title: '新建数据任务', 
		// 		template: require('./views/form.tpl.html'),
		// 		// 初始值定义
		// 		data: {
		// 			tableType: 1
		// 		},
		// 		scope: {
		// 			states: [{
		// 				id: 'base',
		// 				title: '创建任务'
		// 			}, {
		// 				id: 'source',
		// 				title: '数据源配置'
		// 			}, {
		// 				id: 'target',
		// 				title: '目标库设置'
		// 			}, {
		// 				id: 'settings',
		// 				title: '任务设置'
		// 			}, {
		// 				id: 'task',
		// 				title: '定时设置'
		// 			}, {
		// 				id: 'rule',
		// 				title: '配置规则'
		// 			}],
		// 			step: function(i) {
		// 				var el = angular.element('.step-body');
		// 				var scrollTop = 20;
		// 				if (i > 0) {
		// 					scrollTop += 20;
		// 					angular.element('.x-group').each(function(n, el) {
		// 						if (n >= i) {
		// 							return false;
		// 						}
		// 						scrollTop += $(el).outerHeight(true);
		// 					});
		// 				}
		// 				el.animate({
		// 					'scrollTop': scrollTop
		// 				}, 300);
		// 			},
		// 			selectSoruce: function() {
		// 				var _scope = this;
		// 				var _data = _scope.data;
		// 				service.dataSource().then(function(data) {
		// 					_data.source = data;
		// 				});
		// 			},
		// 			selectTable: function() {
		// 				var _scope = this;
		// 				var _data = _scope.data;
		// 				service.dataTable().then(function(tables) {
		// 					_data.tables = tables;
		// 					_scope.checkTable(0);
		// 				});
		// 			},
		// 			checkTable: function(index) {
		// 				var _scope = this;
		// 				var _data = _scope.data;

		// 				_scope.vm.tableNumber = index;

		// 				var table = _data.tables[index];
		// 				_scope.gridOptions.data = table.fields;
		// 				table.type = table.type || 1;
		// 				table.tableName = table.tableName || table.name;
		// 			},
		// 			checkTables: function() {
		// 				var data = this.data;
		// 				return !data.tables || data.tables.length === 0;
		// 			},
		// 			selectLocalTable: function() {
		// 				var _scope = this;
		// 				var _data = _scope.data;
		// 				service.localTable().then(function(data) {
		// 					var table = _data.tables[_scope.vm.tableNumber];
		// 					table.targetId = data.id;
		// 					table.targetName = data.name;
		// 					table.targetFields = data.fields;
		// 				});
		// 			},
		// 			autoApply: function() {
		// 				var _scope = this;

		// 				var api = _scope.api;
		// 				var grid = api.grid;
		// 				var _fields = _scope.fields || [];
		// 				grid.rows.forEach(function(row) {
		// 					var name = grid.getRowValue(row, 'name');
		// 					for (var i = 0, l = _fields.length; i < l; i++) {
		// 						var _meta = _fields[i] || {};
		// 						if (_meta.name == name) {
		// 							grid.setData(row, {
		// 								'sourceMeta': name
		// 							});
		// 							row.isSelected = true;
		// 							break;
		// 						}
		// 					}
		// 				})
		// 			},
		// 			setMeta: function(grid, row, id) {
		// 				grid.setData(row, {
		// 					sourceMeta: id
		// 				});
		// 			},
		// 			setRules: function(grid, row) {
		// 				var _id = grid.getRowValue(row, 'id');
		// 				var loadRulesData = function(scope, params) {
		// 					params = params || {};
		// 					angular.extend(params, {
		// 						type: ''
		// 					});
		// 					return api.gridLoad({
		// 						name: 'meta_rules',
		// 						params: params,
		// 						scope: scope || this
		// 					});
		// 				};
		// 				var rules = grid.getRowValue(row, 'rules');

		// 				api.form({
		// 					title: '选择转换规则',
		// 					template: require('../meta/views/form_rules.tpl.html'),
		// 					beforeSubmit: function(data, deferred) {
		// 						var _scope = this;
		// 						var _data = _scope.gridBufferOptions.data || [];
		// 						var _rules = _data.map(function(r) {
		// 							return {
		// 								id: r.id,
		// 								name: r.name,
		// 								type: r.type,
		// 								options: r.options
		// 							}
		// 						});

		// 						data.rules = _rules;
		// 					},
		// 					scope: {
		// 						q: {},
		// 						fields: {
		// 							type: [{
		// 								id: 1,
		// 								name: '校验规则'
		// 							}, {
		// 								id: 2,
		// 								name: '转换规则'
		// 							}]
		// 						},
		// 						query: function(resetPage) {
		// 							var scope = this;
		// 							if (resetPage === false || scope.gridOptions.paginationCurrentPage == 1) {
		// 								loadRulesData(scope, scope.q);
		// 							} else {
		// 								api.gridReset(null, scope);
		// 							}
		// 						},
		// 						hasSelectedRecords: function(apiName) {
		// 							return api.hasGridSelectedRecords(this, apiName);
		// 						},
		// 						gridOptions: {
		// 							paginationCurrentPage: api.page.pageNumber,
		// 							paginationPageSize: api.page.pageSize,
		// 							useExternalPagination: true,
		// 							multiSelect: false,
		// 							columns: [{
		// 								name: '序号',
		// 								width: 50,
		// 								field: 'id'
		// 							}, {
		// 								name: '规则名称',
		// 								align: 'left',
		// 								width: 200,
		// 								field: 'name'
		// 							}, {
		// 								name: '类型',
		// 								width: 100,
		// 								field: 'type',
		// 								cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col)"></div>'
		// 							}, {
		// 								name: '描述',
		// 								width: 200,
		// 								field: 'desc'
		// 							}],
		// 							forceFit: false,
		// 							onRegisterApi: function(api, grid) {
		// 								var scope = grid.appScope;
		// 								scope.api = api;

		// 								api.pagination && api.pagination.on.paginationChanged(scope, function(newPage, pageSize) {
		// 									scope.query(false);
		// 								});
		// 							}
		// 						},
		// 						add: function() {
		// 							var _scope = this;

		// 							var _data = _scope.gridBufferOptions.data || [];
		// 							var ids = _data.map(function(_r) {
		// 								return _r.id;
		// 							});

		// 							var _add = function(data) {
		// 								var i;
		// 								if ((i = ids.indexOf(data.id)) === -1) {
		// 									_scope.gridBufferOptions.data = [].concat(_data, data);
		// 								} else {
		// 									dialog.confirm('当前规则已在配置列表中，是否覆盖已有配置？').result.then(function() {
		// 										if (r) {
		// 											_scope.gridBufferOptions.data.splice(i, 1, data);
		// 										}
		// 									});
		// 								}
		// 							}

		// 							var data = api.getGridSelectedRecord(_scope);
		// 							var hasParams = data.noParams !== true;
		// 							if (hasParams) {
		// 								var settings;
		// 								switch (data.type) {
		// 									case 2:
		// 										settings = {
		// 											title: '规则配置',
		// 											template: require('../meta/views/form_rule_transform.tpl.html'),
		// 											data: data,
		// 											beforeSettings: function() {
		// 												ConfigApiService.reset().addJson();
		// 											},
		// 											beforeSubmit: function(data) {
		// 												data.options = ConfigApiService.getResultArray();
		// 											},
		// 											scope: {
		// 												addJson: ConfigApiService.addJson,
		// 												jsonArray: ConfigApiService.jsonArray,
		// 												getKey: ConfigApiService.getKey,
		// 												removeJson: ConfigApiService.removeJson,
		// 												movePrev: ConfigApiService.movePrev,
		// 												moveNext: ConfigApiService.moveNext
		// 											}
		// 										}
		// 										break;
		// 									case 1:
		// 									default:
		// 										settings = {
		// 											title: '规则配置',
		// 											template: require('../meta/views/form_rule_params.tpl.html'),
		// 											data: data
		// 										}
		// 								}
		// 								settings && api.form(settings).then(function(data) {
		// 									_add(data);
		// 								});
		// 							} else {
		// 								_add(data);
		// 							}
		// 						},
		// 						edit: function(grid, row) {
		// 							var _scope = this;
		// 							var data = grid.getData(row);
		// 							var id = data.id;
		// 							var _data = _scope.gridBufferOptions.data || [];
		// 							var ids = _data.map(function(_r) {
		// 								return _r.id;
		// 							});
		// 							var i = ids.indexOf(id);

		// 							var settings;
		// 							switch (data.type) {
		// 								case 2:
		// 									settings = {
		// 										title: '规则配置',
		// 										template: require('../meta/views/form_rule_transform.tpl.html'),
		// 										data: data,
		// 										beforeSettings: function() {
		// 											ConfigApiService.setArrayData(data.options);
		// 										},
		// 										beforeSubmit: function(data) {
		// 											data.options = ConfigApiService.getResultArray();
		// 										},
		// 										scope: {
		// 											addJson: ConfigApiService.addJson,
		// 											jsonArray: ConfigApiService.jsonArray,
		// 											getKey: ConfigApiService.getKey,
		// 											removeJson: ConfigApiService.removeJson,
		// 											movePrev: ConfigApiService.movePrev,
		// 											moveNext: ConfigApiService.moveNext
		// 										}
		// 									}
		// 									break;
		// 								case 1:
		// 								default:
		// 									settings = {
		// 										title: '规则配置',
		// 										template: require('../meta/views/form_rule_params.tpl.html'),
		// 										data: data
		// 									}
		// 							}
		// 							settings && api.form(settings).then(function(data) {
		// 								_scope.gridBufferOptions.data.splice(i, 1, data);
		// 							});
		// 						},
		// 						remove: function() {
		// 							var _scope = this;
		// 							var data = _scope.gridBufferOptions.data || [];
		// 							var rs = api.getGridSelectedRecords(_scope, 'bufferApi');
		// 							rs.forEach(function(r) {
		// 								var id = r.id,
		// 									i;
		// 								var ids = data.map(function(_r) {
		// 									return _r.id;
		// 								});
		// 								if ((i = ids.indexOf(id)) !== -1) {
		// 									data.splice(i, 1);
		// 									_scope.bufferApi.selections.removeKey(id);
		// 									_scope.bufferApi.grid.selection.selectedCount--;
		// 								}
		// 							});
		// 						},
		// 						mapping: function(grid, row, col, field) {
		// 							return api.mapping({
		// 								grid: grid,
		// 								row: row,
		// 								col: col,
		// 								field: field,
		// 								scope: this
		// 							});
		// 						},
		// 						gridBufferOptions: {
		// 							enableFullRowSelection: false,
		// 							columns: [{
		// 								name: '序号',
		// 								width: 50,
		// 								field: 'id'
		// 							}, {
		// 								name: '规则名称',
		// 								align: 'left',
		// 								width: 200,
		// 								field: 'name'
		// 							}, {
		// 								name: '类型',
		// 								width: 100,
		// 								field: 'type',
		// 								cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col)"></div>'
		// 							}, {
		// 								name: '描述',
		// 								width: 200,
		// 								field: 'desc'
		// 							}, {
		// 								name: '操作',
		// 								width: 200,
		// 								cellTemplate: '<span class="btn-label" ng-if="grid.getData(row).noParams!=true" ng-click="grid.appScope.edit(grid, row)">修改</span>'
		// 							}],
		// 							forceFit: false,
		// 							onRegisterApi: function(bufferApi, grid) {
		// 								var scope = grid.appScope;
		// 								scope.bufferApi = bufferApi;

		// 								if (bufferApi.selection) {
		// 									grid.registerDataChangeCallback(function() {
		// 										var visibleRows = bufferApi.core.getVisibleRows();
		// 										grid.selection.selectAll = visibleRows.length > 0 && bufferApi.selection.getSelectedCount() === visibleRows.length;
		// 									}, ['row']);
		// 								}
		// 							}
		// 						}
		// 					},
		// 					resolveApply: false,
		// 					resolveWait: function() {
		// 						var _scope = this;
		// 						return {
		// 							grid: function() {
		// 								return loadRulesData(_scope);
		// 							},
		// 							gridBuffer: function() {
		// 								if (rules) {
		// 									_scope.gridBufferOptions.data = [].concat(rules);
		// 									return;
		// 								}
		// 								return api.gridLoad({
		// 									name: 'task_transform_rules',
		// 									params: {
		// 										id: _id
		// 									},
		// 									options: 'gridBufferOptions',
		// 									apiName: 'bufferApi',
		// 									scope: _scope
		// 								});
		// 							}
		// 						}
		// 					},
		// 					config: {
		// 						width: 760
		// 					}
		// 				}).then(function(data) {
		// 					grid.setData(row, data);
		// 				});
		// 			},
		// 			fields: {
		// 				types: [{
		// 					id: 1,
		// 					name: '验'
		// 				}, {
		// 					id: 2,
		// 					name: '转'
		// 				}]
		// 			},
		// 			gridOptions: {
		// 				enableFullRowSelection: false,
		// 				viewportTemplate: '<div class="x-grid-wrap">\
		// 						<div class="x-grid-body">\
		// 							<table cellspacing="0" cellpadding="0">\
		// 								<tbody>\
		// 									<tr ng-repeat="(rowIndex, row) in grid.renderedRows track by $index" ng-class="{\'x-grid-row-selected\':row.isSelected, \'x-grid-row-disabled\': row.enableSelection === false}">\
		// 											<td class="x-grid-group">\
		// 												<table cellspacing="0" cellpadding="0">\
		// 													<tbody>\
		// 														<tr row="row" index="rowIndex" grid-view-row></tr>\
		// 													</tbody>\
		// 												</table>\
		// 												<div class="x-field-group" ng-if="grid.getRowValue(row, \'rules\').length > 0">\
		// 													<div class="x-field">\
		// 														<div class="x-field-header">\
		// 															<h4><label><i class="fa fa-info-circle"></i> 当前规则</label></h4>\
		// 														</div>\
		// 														<div class="x-field-body">\
		// 															<div class="x-tag-affix">\
		// 																<ul>\
		// 																	<li class="affix-{{rule.type}}" ng-repeat="rule in grid.getRowValue(row, \'rules\') track by $index"><em>{{rule.type| mapping:grid.appScope.fields.types:\'id\'}}</em>{{rule.name}}</li>\
		// 																</ul>\
		// 															</div>\
		// 														</div>\
		// 													</div>\
		// 												</div>\
		// 											</td>\
		// 										</tr>\
		// 									</tbody>\
		// 								</table>\
		// 							</div>\
		// 						</div>',
		// 				columns: [{
		// 					name: '序号',
		// 					width: 42,
		// 					cellTemplate: '<div class="x-grid-inner">{{index+1}}</div>'
		// 				}, {
		// 					name: '数据表字段',
		// 					width: 200,
		// 					field: 'name'
		// 				}, {
		// 					name: '数据类型',
		// 					width: 150,
		// 					field: 'dataType'
		// 				}, {
		// 					name: '源值',
		// 					width: 200,
		// 					cellTemplate: '<div class="x-grid-inner"><input ng-if="grid.appScope.data.tables[grid.appScope.vm.tableNumber].type==1" type="text" ng-model="row.entity.sourceMeta" ng-init="row.entity.sourceMeta=row.entity.sourceMeta||grid.getRowValue(row, \'name\')" required class="x-ipt" placeholder="请输入目标字段名称" /><select ng-if="grid.appScope.data.tables[grid.appScope.vm.tableNumber].type==2" ng-model="row.entity.sourceMeta" ng-change="setMeta(grid, row, row.entity.sourceMeta)" ng-options="m.id as m.name for m in grid.appScope.data.tables[grid.appScope.vm.tableNumber].targetFields" required><option value="">请选择源</option></select></div>'
		// 				}, {
		// 					name: '同步',
		// 					width: 120,
		// 					cellTemplate: '<label data-toggle><input type="checkbox" ng-model="row.entity.sync" ng-init="row.entity.sync=row.entity.sync==null?1:row.entity.sync" class="x-chk" ng-true-value="1" ng-false-value="0" /></label>'
		// 				}, {
		// 					name: '处理方式',
		// 					width: 150,
		// 					cellTemplate: '<span class="btn-label" ng-click="grid.appScope.setRules(grid, row)">数据规则</span>'
		// 				}],
		// 				forceFit: false,
		// 				data: [],
		// 				onRegisterApi: function(api, grid) {
		// 					var _scope = grid.appScope;
		// 					_scope.api = api;
		// 				}
		// 			}
		// 		},
		// 		vm: {

		// 		},
		// 		config: {
		// 			width: '70%'
		// 		},
		// 		afterRendered: function() {
		// 			var el = angular.element('.step-body');
		// 			var triggers = angular.element('.step-node');
		// 			var panels = angular.element('.x-group');
		// 			var top = panels.eq(1).offset().top;
		// 			var _top = top - panels.eq(0).height() - 20;

		// 			el.on('scroll.task', function() {
		// 				var scrollTop = el.scrollTop();
		// 				triggers.removeClass('step-hover');
		// 				panels.each(function(n) {
		// 					var panel = $(this);
		// 					var top = panel.offset().top - _top + 20;
		// 					if (top <= 0) {
		// 						triggers.eq(n).addClass('step-hover');
		// 					}
		// 				})
		// 			});

		// 			this.$on('$destroy', function() {
		// 				el.off('scroll.task');
		// 			});
		// 		}
		// 	}).then(function() {
		// 		query();
		// 	});
		// }
		
		var from = 'from', 
			to = 'to',
			vs = 'vs',
			meta = 'meta',
			sync = 'sync';

		function addSql() {
			var _scope = this;
			var vm = _scope.vm;
			var data = _scope.data;
			var task = data.tasks[vm.index];
			task[vm.vs].sql = task[vm.vs].sql || [];

			// 默认设置
			var sql = {
				condition: 'and'
			};

			task[vm.vs].sql.unshift(sql);
			_scope.addCriteria(0);
		}
		function removeSql(index) {
			var _scope = this;
			var vm = _scope.vm;
			var data = _scope.data;
			var task = data.tasks[vm.index];
			if (!task[vm.vs].sql || task[vm.vs].sql.length === 0) return;

			task[vm.vs].sql.splice(index, 1);
		}
		function addCriteria(index) {
			var _scope = this;
			var vm = _scope.vm;
			var data = _scope.data;
			var task = data.tasks[vm.index];
			if (!task[vm.vs].sql || task[vm.vs].sql.length === 0) return;

			var sql = task[vm.vs].sql[index];
			sql.criteria = sql.criteria || [];

			// 默认设置
			var criteria = {
				type: '1',
				condition: 'and'
			};
			// sql.criteria.unshift(criteria);
			sql.criteria.push(criteria);
		}
		function removeCriteria(index, m) {
			var _scope = this;
			var vm = _scope.vm;
			var data = _scope.data;
			var task = data.tasks[vm.index];
			if (!task[vm.vs].sql || task[vm.vs].sql.length === 0) return;

			var sql = task[vm.vs].sql[index];
			if (!sql.criteria || sql.criteria === 0) return;

			sql.criteria.splice(m, 1);
		}
		
		$scope.add = function() {
			api.form({
				title: '新建数据任务', 
				template: require('./views/form.tpl.html'),
				// 初始值定义
				data: {
					
				},
				beforeSettings: function() {
					this.addTask();
				},
				scope: {
					addTask: function() {
						var _scope = this;
						var data = _scope.data;
						data.tasks = data.tasks || [];
						var vm = _scope.vm;
						vm.index = data.tasks.length;
						var task = {};
						task[from] = {
								table: '新增配置'
							};
						data.tasks.push(task)
					},
					activeTask: function(index) {
						var _scope = this;
						var vm = _scope.vm;
						var data = _scope.data;

						_scope.vm.index = index;
						if (data.tasks[index][vm.to]) {
							_scope.gridOptions.data = data.tasks[index][vm.to].fields;
						}
					},
					removeTask: function(index) {
						var _scope = this.$parent;
						var data = _scope.data;

						if (_scope.vm.index > 0) _scope.vm.index--;
						data.tasks.splice(index, 1);
					},
					dataSource: function() {
						var _scope = this;
						var vm = _scope.vm;
						var data = _scope.data;
						var task = data.tasks[vm.index];
						service.dataSource().then(function(_data) {
							task[from] = _data;
							$timeout(function() {
								_scope.autoApply();
								_scope.sync();
							}, 0);
						});
					},
					dataLocalSource: function() {
						var _scope = this;
						var vm = _scope.vm;
						var data = _scope.data;
						var task = data.tasks[vm.index];
						if (!task) {
							task = data.tasks[vm.index] = {};
						}
						service.dataLocalSource(task[from]).then(function(_data) {
							task[to] = _data;
							_scope.gridOptions.data = _data.fields;
							$timeout(function() {
								_scope.autoApply();
								_scope.sync();
							}, 0);
						});
					},
					dataCompareSource: function() {
						var _scope = this;
						var vm = _scope.vm;
						var data = _scope.data;
						var task = data.tasks[vm.index];
						if (!task) {
							task = data.tasks[vm.index] = {};
						}
						service.dataCompareSource().then(function(_data) {
							task[vs] = _data;

							_scope.addSql();
						});
					},
					autoApply: function() {
						var _scope = this;
						var vm = _scope.vm;
						var api = _scope.api;
						if (!api) return;
						var grid = api.grid;

						var _from = _scope.data.tasks[vm.index][vm.from];
						if (!_from) return;
						var _fields = _from.fields || [];
						if (_fields.length && grid.rows.length) {
							grid.rows.forEach(function(row) {
								var name = grid.getRowValue(row, 'name');
								for (var i = 0, l = _fields.length; i < l; i++) {
									var _meta = _fields[i] || {};
									if (_meta.name == name) {
										var data = {};
										data[meta] = name;
										grid.setData(row, data);
										// row.isSelected = true;
										break;
									}
								}
							});
						}
					},
					sync: function() {
						var _scope = this;
						var vm = _scope.vm;

						var api = _scope.api;
						if (!api) return;
						var grid = api.grid;
						if (!grid) return;
						var _from = _scope.data.tasks[vm.index][vm.from];
						if (!_from) return;
						var _fields = _from.fields || [];
						if (_fields.length && grid.rows.length) {
							grid.rows.forEach(function(row) {
								var data = {};
								data[sync] = data[sync] == null ? 1 : grid.getRowValue(row, sync);
								grid.setData(row, data);
							});
						}
					},
					setMeta: function(grid, row, id) {
						var data = {};
						data[meta] = id;
						grid.setData(row, data);
					},
					setTableRules: function() {
						var _scope = this.$parent;
						var vm = _scope.vm;
						var data = _scope.data;
						var task = data.tasks[vm.index];
						var rules = task[to].rules;

						service.dataRules(1, {
							// id: 1
						}, rules).then(function(_data) {
							task[to].rules = _data.rules;
						});
					},
					setFieldRules: function(grid, row) {
						var _scope = this.$parent;
						var vm = _scope.vm;
						var data = _scope.data;
						var task = data.tasks[vm.index];

						var _id = grid.getRowValue(row, 'id');
						var rules = grid.getRowValue(row, 'rules');
						service.dataRules(2, {
							id: _id
						}, rules, {
							fields: task[from].fields
						}).then(function(_data) {
							grid.setData(row, _data);
						});
					},
					setVsRules: function(index, m) {
						var _scope = this;
						var vm = _scope.vm;
						var data = _scope.data;
						var task = data.tasks[vm.index];

						var sql = task[vm.vs].sql[index];
						var criteria = sql.criteria[m];
						var rules = criteria.rules;

						service.dataRules(2, {

						}, rules).then(function(_data) {
							criteria.rules = _data.rules;
						});
					},
					addSql: addSql,
					removeSql: removeSql,
					addCriteria: addCriteria,
					removeCriteria: removeCriteria,
					gridOptions: {
						enableFullRowSelection: false,
						viewportTemplate: '<div class="x-grid-wrap">\
								<div class="x-grid-body">\
									<table cellspacing="0" cellpadding="0">\
										<tbody>\
											<tr ng-repeat="(rowIndex, row) in grid.renderedRows track by $index" ng-class="{\'x-grid-row-selected\':row.isSelected, \'x-grid-row-disabled\': row.enableSelection === false}">\
													<td class="x-grid-group">\
														<table cellspacing="0" cellpadding="0">\
															<tbody>\
																<tr row="row" index="rowIndex" grid-view-row></tr>\
															</tbody>\
														</table>\
														<div class="x-field-group" ng-if="grid.getRowValue(row, \'rules\').length > 0">\
															<div class="x-field">\
																<div class="x-field-header">\
																	<h4><label><i class="fa fa-info-circle"></i> 当前规则</label></h4>\
																</div>\
																<div class="x-field-body">\
																	<div class="x-tag-affix">\
																		<ul>\
																			<li class="affix-{{rule.type}}" ng-repeat="rule in grid.getRowValue(row, \'rules\') track by $index"><em>{{rule.type | mapping:grid.appScope.vm.fields.types:\'id\'}}</em>{{rule.name}}</li>\
																		</ul>\
																	</div>\
																</div>\
															</div>\
														</div>\
													</td>\
												</tr>\
											</tbody>\
										</table>\
									</div>\
								</div>',
						columns: [{
							name: '主键',
							width: 42,
							cellTemplate: '<div class="x-grid-inner field-primary" ng-click="grid.appScope.$parent.data.tasks[grid.appScope.$parent.vm.index][grid.appScope.$parent.vm.to].primary=row.entity.name"><i class="fa fa-key" ng-if="grid.appScope.$parent.data.tasks[grid.appScope.$parent.vm.index][grid.appScope.$parent.vm.to].primary==row.entity.name"></i></div>'
						}, {
							name: '序号',
							width: 42,
							cellTemplate: '<div class="x-grid-inner">{{index+1}}</div>'
						}, {
							name: '目标字段',
							width: 300,
							field: 'name',
							cellTemplate: '<div class="x-grid-inner">{{grid.getCellValue(row, col)}}<span class="text-info" ng-if="grid.getRowValue(row, \'text\')">（{{grid.getRowValue(row, \'text\')}}）</span></div>'
						}, {
							name: '数据类型',
							width: 120,
							field: 'dataType'
						}, {
							name: '源字段',
							width: 300,
							cellTemplate: '<div class="x-grid-inner"><select ng-model="row.entity[grid.appScope.$parent.vm.meta]" ng-change="setMeta(grid, row, row.entity[grid.appScope.$parent.vm.meta])" ng-options="m.name as (m.name + (m.text ? \'（\' + m.text + \'）\' : \'\')) for m in grid.appScope.$parent.data.tasks[grid.appScope.$parent.vm.index][grid.appScope.$parent.vm.from].fields" required><option value="">请选择源</option></select></div>'
						}, {
							name: '同步',
							width: 100,
							cellTemplate: '<label data-toggle><input type="checkbox" ng-model="row.entity.sync" class="x-chk" ng-true-value="1" ng-false-value="0" /></label>'
						}, {
							name: '处理方式',
							width: 150,
							cellTemplate: '<span class="btn-label" ng-click="grid.appScope.setFieldRules(grid, row)">数据规则</span>'
						}],
						forceFit: false,
						data: [],
						onRegisterApi: function(api, grid) {
							var _scope = grid.appScope.$parent;
							_scope.api = api;
						}
					}
				},
				vm: {
					states: [{
						id: 'base',
						title: '创建任务'
					}, {
						id: 'rule',
						title: '配置规则'
					}, {
						id: 'settings',
						title: '任务设置'
					}, {
						id: 'task',
						title: '定时设置'
					}],
					step: function(i) {
						var el = angular.element('.x-data-panel-body');
						var scrollTop = 0;
						if (i > 0) {
							scrollTop += 20;
							el.find('.x-group').each(function(n, el) {
								if (n >= i) {
									return false;
								}
								scrollTop += $(el).outerHeight(true);
							});
						}
						el.animate({
							'scrollTop': scrollTop
						}, 300);
					},
					from: from,
					to: to,
					vs: vs,
					meta: meta,
					sync: sync,
					fields: {
						types: [{
							id: 1,
							name: '验'
						}, {
							id: 2,
							name: '转'
						}]
					}
				},
				config: {
					width: '70%'
				},
				// afterRendered: function() {
				// 	var el = angular.element('.x-data-panel-body');
				// 	var triggers = angular.element('.x-step');
				// 	var panels = el.find('.x-group');
				// 	var top = panels.eq(1).offset().top;
				// 	var _top = top - panels.eq(0).height();

				// 	el.on('scroll.task', function() {
				// 		var scrollTop = el.scrollTop();
				// 		triggers.removeClass('active');
				// 		panels.each(function(n) {
				// 			var panel = $(this);
				// 			var top = panel.offset().top - _top + 20;
				// 			if (top <= 0) {
				// 				triggers.eq(n).addClass('active');
				// 			}
				// 		})
				// 	});

				// 	this.$on('$destroy', function() {
				// 		el.off('scroll.task');
				// 	});
				// }
				afterRendered: function() {
					var el = angular.element('.x-data-panel-body');
					var triggers = angular.element('.x-step');
					var panels = el.find('.x-group');
					triggers.eq(0).addClass('active');
					var _top = el.offset().top;

					el.on('scroll.task', function() {
						var scrollTop = el.scrollTop();
						triggers.removeClass('active');
						panels.each(function(n) {
							var panel = $(this);
							// var top = 0;
							// for (var i=0; i<n; i++) {
							// 	top += panels.eq(i).height() + 20;
							// }
							var top = panel.offset().top - _top - 20;
							// top += scrollTop;
							// if (scrollTop >= top && scrollTop < top + panel.height() + 20) {
							if (0 >= top && 0 < top + panel.height() + 20) {
								triggers.eq(n).addClass('active');
							}
						})
					});

					this.$on('$destroy', function() {
						el.off('scroll.task');
					});
				}
			}).then(function() {
				query();
			});
		}

		$scope.log = function(id) {
			var loadLogsData = function(scope, params) {
				scope = scope || this;
				params = params || {};
				angular.extend(params, {
					id: id
				});
				return api.gridLoad({
					name: 'task_logs', 
					params: params,
					scope: scope
				});
			};
			api.form({
				title: '日志记录',
				template: require('./views/form_logs.tpl.html'),
				scope: {
					q: {},
					gridOptions: {
						paginationCurrentPage: api.page.pageNumber,
						paginationPageSize: api.page.pageSize,
						useExternalPagination: true,
						multiSelect: false,
						columns: [{
							name: '序号',
							width: 50,
							cellTemplate: '<div class="x-grid-inner">{{index+1}}</div>'
						}, {
							name: '存档日期',
							field: 'date'
						}, {
							name: '操作',
							width: 150,
							field: 'id',
							cellTemplate: '<div class="x-grid-inner"><span class="btn-text" ng-click="grid.appScope.preview(grid.getCellValue(row, col))">查看详情</span></div>'
						}],
						data: [],
						onRegisterApi: function(api, grid) {
							var _scope = grid.appScope;
							_scope.api = api;

							api.pagination && api.pagination.on.paginationChanged(_scope, function(newPage, pageSize) {
								_scope.query(false);
							});
						}
					},
					query: function(resetPage, params) {
						var _scope = this;
						if (resetPage === false || _scope.gridOptions.paginationCurrentPage == 1) {
							var _params = angular.merge({}, _scope.q, params);
							loadLogsData(_scope, _params);
						} else {
							api.gridReset(null, _scope);
						}
					},
					preview: function(cid) {
						api.form({
							title: '日志详情',
							template: require('./views/form_preview.tpl.html'),
							resolveWait: http.post({
								name: 'task_log',
								params: {
									id: id,
									cid: cid
								}
							})
						})
					}
				},
				resolveApply: false,
				resolveWait: function() {
					var _scope = this;
					return loadLogsData(_scope);
				}
			})
		}

		/**
		 * 运行中
		 */
		var loadData = $scope.loadData = function(params) {
				api.gridLoad({
					name: 'tasks', 
					params: params,
					scope: $scope
				});
			};

	    var query = $scope.query = function(resetPage) {
			if (resetPage === false || $scope.gridOptions.paginationCurrentPage == 1) {
				loadData(q);
			} else {
				api.gridReset(null, $scope);
			}
		}

		$scope.gridOptions = {
			showHeader: false,
			enableRowSelection: true,
			enableRowHeaderSelection: false,
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			showEmptyTips: false,
			paginationTemplate: 'grid/ui-paging',
			dataView: {
				field: 'name',
				itemAddTemplate: 
							'<div class="ui-grid-item ui-item-add" ng-click="grid.appScope.add()">\
								<div class="ui-item-add-toolbar"><button type="button" class="btn-add"><span class="text-inner">新建任务</span></button></div>\
							</div>',
				rowTemplate: 
						'<div class="ui-grid-item-body">\
							<div class="ui-item-toolbar">\
								<span class="ui-item-date text-warning">{{grid.getRowValue(row, \'date\')}}</span>\
							</div>\
							<div class="data-task">\
								<ul>\
									<li><i class="fa fa-database"></i> Mysql</li>\
									<li><i class="fa fa-server"></i> Hbase</li>\
								</ul>\
							</div>\
							<div class="ui-item-state">\
								<span class="text-success">运行中</span>\
							</div>\
						</div>\
						<div class="ui-grid-item-detail">\
							<h4 ng-if="grid.getRowValue(row, field)" title="{{grid.getRowValue(row, field)}}">{{grid.getRowValue(row, field)}}</h4>\
							<div class="ui-grid-item-body">\
								<div class="ui-item-toolbar">\
									<span class="ui-item-date text-warning">{{grid.getRowValue(row, \'date\')}}</span>\
								</div>\
								<div class="data-task">\
									<ul>\
										<li><i class="fa fa-database"></i> Mysql</li>\
										<li><i class="fa fa-server"></i> Hbase</li>\
									</ul>\
								</div>\
								<div class="ui-item-state">\
									<span class="text-success">运行中</span>\
								</div>\
							</div>\
							<div class="ui-grid-item-tools"><span ng-repeat="c in tools track by $index" class="fa fa-{{getRowClass(grid, row, c)}} ico-btn" ng-disabled="rowDisabled(grid, row, c)" ng-if="rowVisible(grid, row, c)" ng-click="c.handler(grid, row, c, $event)" title="{{c.title||c.text}}" ng-bind-html="c.text"></span></div>\
						</div>',
				tools: [{
					icoCls: 'edit',
					title: '修改'
				}, {
					name: 'pause',
					icoCls: 'pause-circle',
					title: '暂停'
				}, {
					name: 'start',
					title: '恢复',
					icoCls: 'play-circle'
				}, {
					name: 'remove',
					icoCls: 'trash-o',
					title: '删除'
				}, {
					name: 'log',
					icoCls: 'paw',
					title: '查看日志'
				}]
			},
			onRegisterApi: function(api) {
				$scope.api = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					query(false);
				});
			}
		};

		query();

		/**
		 * 运行错误
		 */
		var loadErrorData = $scope.loadErrorData = function(params) {
				api.gridLoad({
					name: 'tasks', 
					params: params,
					scope: $scope,
					apiName: 'errorApi',
					options: 'gridErrorOptions',
				});
			};

	    var queryError = $scope.queryError = function(resetPage) {
			if (resetPage === false || $scope.gridErrorOptions.paginationCurrentPage == 1) {
				loadErrorData(q);
			} else {
				api.gridReset('gridErrorOptions', $scope);
			}
		}

		$scope.gridErrorOptions = {
			showHeader: false,
			enableRowSelection: true,
			enableRowHeaderSelection: false,
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			paginationTemplate: 'grid/ui-paging',
			dataView: {
				field: 'name',
				rowTemplate: 
						'<div class="ui-grid-item-body">\
							<div class="ui-item-toolbar">\
								<span class="ui-item-date text-warning">{{grid.getRowValue(row, \'date\')}}</span>\
							</div>\
							<div class="data-task">\
								<ul>\
									<li><i class="fa fa-database"></i> Mysql</li>\
									<li><i class="fa fa-server"></i> Hbase</li>\
								</ul>\
							</div>\
							<div class="ui-item-state">\
								<span class="text-danger">发生异常</span>\
							</div>\
						</div>',
				tools: [{
					icoCls: 'edit',
					title: '修改'
				}, {
					name: 'pause',
					icoCls: 'pause-circle',
					title: '暂停'
				}, {
					name: 'start',
					title: '恢复',
					icoCls: 'play-circle'
				}, {
					name: 'remove',
					icoCls: 'trash-o',
					title: '删除'
				}, {
					name: 'log',
					icoCls: 'paw',
					title: '查看日志'
				}]
			},
			onRegisterApi: function(api) {
				$scope.errorApi = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					queryError(false);
				});
			}
		};

		queryError();

		/**
		 * 可运行
		 */
		var loadMasterData = $scope.loadMasterData = function(params) {
				api.gridLoad({
					name: 'tasks', 
					params: params,
					scope: $scope,
					apiName: 'masterApi',
					options: 'gridMasterOptions',
				});
			};

	    var queryMaster = $scope.queryMaster = function(resetPage) {
			if (resetPage === false || $scope.gridMasterOptions.paginationCurrentPage == 1) {
				loadMasterData(q);
			} else {
				api.gridReset('gridMasterOptions', $scope);
			}
		}

		$scope.gridMasterOptions = {
			showHeader: false,
			enableRowSelection: true,
			enableRowHeaderSelection: false,
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			paginationTemplate: 'grid/ui-paging',
			dataView: {
				field: 'name',
				rowTemplate: 
						'<div class="ui-grid-item-body">\
							<div class="ui-item-toolbar">\
								<span class="ui-item-date text-warning">{{grid.getRowValue(row, \'date\')}}</span>\
							</div>\
							<div class="data-task">\
								<ul>\
									<li><i class="fa fa-database"></i> Mysql</li>\
									<li><i class="fa fa-server"></i> Hbase</li>\
								</ul>\
							</div>\
							<div class="ui-item-state">\
								<span class="text-info">等待运行</span>\
							</div>\
						</div>',
				tools: [{
					icoCls: 'edit',
					title: '修改'
				}, {
					name: 'pause',
					icoCls: 'pause-circle',
					title: '暂停'
				}, {
					name: 'start',
					title: '恢复',
					icoCls: 'play-circle'
				}, {
					name: 'remove',
					icoCls: 'trash-o',
					title: '删除'
				}, {
					name: 'log',
					icoCls: 'paw',
					title: '查看日志'
				}]
			},
			onRegisterApi: function(api) {
				$scope.masterApi = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					queryMaster(false);
				});
			}
		};

		queryMaster();

		/**
		 * 待完善
		 */
		var loadSlaveData = $scope.loadSlaveData = function(params) {
				api.gridLoad({
					name: 'tasks', 
					params: params,
					scope: $scope,
					apiName: 'slaveApi',
					options: 'gridSlaveOptions',
				});
			};

	    var querySlave = $scope.querySlave = function(resetPage) {
			if (resetPage === false || $scope.gridSlaveOptions.paginationCurrentPage == 1) {
				loadSlaveData(q);
			} else {
				api.gridReset('gridSlaveOptions', $scope);
			}
		}

		$scope.gridSlaveOptions = {
			showHeader: false,
			enableRowSelection: true,
			enableRowHeaderSelection: false,
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			paginationTemplate: 'grid/ui-paging',
			dataView: {
				field: 'name',
				rowTemplate: 
						'<div class="ui-grid-item-body">\
							<div class="ui-item-toolbar">\
								<span class="ui-item-date text-warning">{{grid.getRowValue(row, \'date\')}}</span>\
							</div>\
							<div class="data-task">\
								<ul>\
									<li><i class="fa fa-database"></i> Mysql</li>\
									<li><i class="fa fa-server"></i> Hbase</li>\
								</ul>\
							</div>\
							<div class="ui-item-state">\
								<span class="text-warning">待完善</span>\
							</div>\
						</div>',
				tools: [{
					icoCls: 'edit',
					title: '修改'
				}, {
					name: 'pause',
					icoCls: 'pause-circle',
					title: '暂停'
				}, {
					name: 'start',
					title: '恢复',
					icoCls: 'play-circle'
				}, {
					name: 'remove',
					icoCls: 'trash-o',
					title: '删除'
				}, {
					name: 'log',
					icoCls: 'paw',
					title: '查看日志'
				}]
			},
			onRegisterApi: function(api) {
				$scope.slaveApi = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					querySlave(false);
				});
			}
		};

		querySlave();
	}
}